Page({
  data: {
    imgW: 0,
    imgH: 0,
    imgUrls: [],
  },
  imgSrc: '',
  onReady() {
    wx.createSelectorQuery().select('#canvas').fields({
      node: true,
      size: true
    }).exec(res => {
      const canvas = this.canvas = res[0].node
      this.ctx = canvas.getContext('2d')
      this.dpr = wx.getWindowInfo().pixelRatio
      // this.ctx.scale(this.dpr, this.dpr)
    })
  },
  async chooseImage() {
    wx.showActionSheet({
      itemList: ['从聊天会话选择', '从相册选择', '拍照'],
      success: async res => {
        if (res.tapIndex === 0) {
          let res2 = await wx.chooseMessageFile({
            count: 1,
            type: 'image',
          })
          this.imgSrc = res2.tempFiles[0].path
        } else if (res.tapIndex === 1) {
          // 选择本地图片
          let res2 = await wx.chooseMedia({
            count: 1,
            mediaType: ['image'],
            sourceType: ['album'],
            sizeType: ['original'],
          })
          this.imgSrc = res2.tempFiles[0].tempFilePath
        } else {
          // 选择本地图片
          let res2 = await wx.chooseMedia({
            count: 1,
            mediaType: ['image'],
            sourceType: ['camera'],
            sizeType: ['original'],
          })
          this.imgSrc = res2.tempFiles[0].tempFilePath
        }
        console.log('图片信息', this.imgSrc)
        await this.drawImageToCanvas()
      },
      fail: err => {
        console.log(err.errMsg)
      }
    })
  },
  // 选择图片，并绘制到canvas画布
  async drawImageToCanvas() {
    try {
      // 根据本地图片尺寸，重置canvas尺寸
      let res2 = await wx.getImageInfo({
        src: this.imgSrc
      })
      console.log('图片尺寸：', res2.width, res2.height)
      const canvas = this.canvas

      this.setData({
        canvasW: canvas.width = res2.width,
        canvasH: canvas.height = res2.height,
      })

      let pic = canvas.createImage()
      pic.src = this.imgSrc
      pic.onload = () => {
        this.ctx.drawImage(pic, 0, 0, canvas.width, canvas.height)
        this.setData({
          imgUrls: [this.imgSrc]
        })
      }
    } catch (error) {
      console.error('取消操作', error)
    }
  },
  // 切图
  async imageCut(e) {
    if (!this.imgSrc) {
      wx.showToast({
        title: '请先选择图片',
        icon: 'error'
      })
      return
    }
    let {
      type
    } = e.currentTarget.dataset
    let cutType = [
      [
        [0, 0],
        [1, 0],
        [0, 1],
        [1, 1]
      ],
      [
        [0, 0],
        [1, 0],
        [2, 0],
        [0, 1],
        [1, 1],
        [2, 1]
      ],
      [
        [0, 0],
        [1, 0],
        [2, 0],
        [0, 1],
        [1, 1],
        [2, 1],
        [0, 2],
        [1, 2],
        [2, 2]
      ]
    ]
    let imgUrls = []
    let cutW = this.data.canvasW / (type === 0 ? 2 : 3)
    let cutH = this.data.canvasH / (type === 2 ? 3 : 2)
    for (let index = 0; index < cutType[type].length; index++) {
      const item = cutType[type][index];
      try {
        wx.showLoading({
          title: `正在裁剪第${index+1}张`,
          mask: true
        })
        let res = await wx.canvasToTempFilePath({
          x: cutW * item[0],
          y: cutH * item[1],
          width: cutW,
          height: cutH,
          destWidth: cutW,
          destHeight: cutH,
          canvas: this.canvas
        })
        imgUrls.push(res.tempFilePath)
        if (index === cutType[type].length - 1) {
          wx.hideLoading()
          this.setData({
            imgUrls
          })
        }
      } catch (error) {
        wx.showToast({
          title: '图片裁剪失败',
          icon: 'error'
        })
        console.error(error)
      }
      await sleep(1000)
    }
  },
  // 预览图片
  previewImage(e) {
    let {
      index
    } = e.currentTarget.dataset
    wx.previewImage({
      current: this.data.imgUrls[index],
      urls: this.data.imgUrls,
      showmenu: true
    })
  },
  // 保存所有图片
  saveAll() {
    if (this.data.imgUrls.length === 0) {
      wx.showToast({
        title: '请先上传图片',
        icon: 'error'
      })
      return
    }
    this.data.imgUrls.forEach(async (item, index) => {
      wx.showLoading({
        title: `正在保存第${index+1}张`,
        mask: true
      })
      await wx.saveImageToPhotosAlbum({
        filePath: item
      })
      if (index === this.data.imgUrls.length - 1) {
        wx.showToast({
          title: '已保存至相册',
          icon: 'success'
        })
      }
    })
  },
  onShareAppMessage() {
    return {
      title: "多宫格切图，一张图切成469等",
      path: "/pages/imageTools/pages/gongGe/index",
      imageUrl: '/images/function_icon/gong_ge.png',
    }
  },
  onShareTimeline() {
    return {
      title: '多宫格切图，一张图切成469等',
      imageUrl: '/images/function_icon/gong_ge.png',
    }
  },
})

function sleep(ms) {
  console.log('延时=========')
  return new Promise(resolve => setTimeout(resolve, ms))
}